package com.delayqueue.master.netty.handler.registry;

import com.delayqueue.common.netty.handler.ExceptionHandler;
import com.delayqueue.common.netty.handler.MessageToStringEncoder;
import com.delayqueue.common.netty.handler.StringToByteEncoder;
import com.delayqueue.master.config.NettyConfig;
import com.delayqueue.master.config.RegistryConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RegistryConnectBootstrap {

    @Autowired
    private RegistryConfig registryConfig;

    @Autowired
    private RegistryConnectHandler registryConnectHandler;

    public void connect() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(NettyConfig.worker);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {

                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast(new StringToByteEncoder());
                pipeline.addLast(new MessageToStringEncoder());

                pipeline.addLast(registryConnectHandler);
                pipeline.addLast(new ExceptionHandler());
            }
        });
        ChannelFuture future = bootstrap.connect(registryConfig.getIp(), registryConfig.getPort());
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (!channelFuture.isSuccess()) {
                    log.info("连接注册中心失败，正在重试");
                    channelFuture.channel().eventLoop().schedule(new Runnable() {
                        @Override
                        public void run() {
                            connect();
                        }
                    }, 1, TimeUnit.SECONDS);
                }
            }
        });
    }
}
